﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Reflection;
using Microsoft.Office.Interop.Excel;

namespace AccelerationTimeHistoryGen
{
    class ATHColumnMaker
    {
        private string mPath;
        /// <summary>
        /// Acceleration Time Histories
        /// </summary>
        private List<string> mATH = new List<string>();
        public int MaxValues { get; set; }
        /// <summary>
        /// Time Interval in Milliseconds
        /// </summary>
        public int DT { get; set; }
        private Microsoft.Office.Interop.Excel.Application mExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
        private Microsoft.Office.Interop.Excel.Workbook mWorkBook;
        private Microsoft.Office.Interop.Excel.Sheets mWorkSheets;

        public string ExcelFilePath { get; set; }

        private string mXlsFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "data.xlsx");

        private Microsoft.Office.Interop.Excel.Worksheet mWSheet1 = new Microsoft.Office.Interop.Excel.WorksheetClass();

        public Microsoft.Office.Interop.Excel.Worksheet WorkSheet1
        {
            get { return mWSheet1; }
        }

        public ATHColumnMaker(string p)
        {
            this.DT = 20;
            this.mPath = p;

            mExcelApp.DisplayAlerts = false;
            mWorkBook = mExcelApp.Workbooks.Open(mXlsFilePath, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        }

        /// <summary>
        /// Creates a column from an ATH file generated by Shake91
        /// </summary>
        public void MakeColumn(int maxValues)
        {
            StreamReader sr = new StreamReader(mPath);
            string line = sr.ReadLine();
            line = sr.ReadLine();
            line = sr.ReadLine();
            if (IsValidLine(line))
            {
                while (mATH.Count < maxValues)
                {
                    AddAccelelations(line);
                    line = sr.ReadLine();
                }
            }
            sr.Close();

            string dest = Path.Combine(Path.GetDirectoryName(mPath), Path.GetFileNameWithoutExtension(mPath) + "-for-excel.txt");
            StreamWriter sw = new StreamWriter(dest);
            foreach (string s in mATH)
            {
                sw.WriteLine(s);
            }
            sw.Close();

            //************************
            //* Initialize Worksheets
            //************************
            mWorkSheets = mWorkBook.Worksheets;
            mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");

            FillData(mWSheet1);
            AutofitColumns(mWSheet1, "A1", "N1");
            ExcelFilePath = SaveAs2003(Path.GetDirectoryName(mPath), Path.GetFileNameWithoutExtension(mPath));
            mExcelApp.Quit();
        }

        private void FillData(Microsoft.Office.Interop.Excel.Worksheet ws)
        {
            for (int i = 0; i < mATH.Count; i++)
            {
                ws.Cells[i + 1, 1] = (decimal)(i * DT / 1000.0);
                ws.Cells[i + 1, 2] = mATH[i];
            }

            GenerateChart(ws);
        }

        private void GenerateChart(Worksheet ws)
        {
            try
            {
                // Now create the chart.
                ChartObjects chartObjs = (ChartObjects)ws.ChartObjects(Type.Missing);
                ChartObject chartObj = chartObjs.Add(100, 20, 960, 540);
                Chart xlChart = chartObj.Chart;

                //Range chartRange = ws.get_Range("A1", "B" + mATH.Count);
                //xlChart.SetSourceData(chartRange, Type.Missing);
          

                SeriesCollection seriesCollection = (SeriesCollection)xlChart.SeriesCollection(Type.Missing);
                seriesCollection.NewSeries();
                seriesCollection.Item(1).XValues = "=Sheet1!$A:$A";
                seriesCollection.Item(1).Values = "=Sheet1!$B:$B";
                xlChart.ChartType = XlChartType.xlXYScatterSmoothNoMarkers;

                // Customize axes:
                Axis xAxis = (Axis)xlChart.Axes(XlAxisType.xlCategory,
                    XlAxisGroup.xlPrimary);
                xAxis.HasTitle = true;
                xAxis.AxisTitle.Text = "Time (s)";

                Axis yAxis = (Axis)xlChart.Axes(XlAxisType.xlValue,
                    XlAxisGroup.xlPrimary);
                yAxis.HasTitle = true;
                yAxis.AxisTitle.Text = "Acceleration (g)";

                // Add title:
                xlChart.HasTitle = true;
                xlChart.ChartTitle.Text = "Acceleration Time History";

                // Remove legend:
                xlChart.HasLegend = false;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                mExcelApp.Quit();
            }

        }

        public string SaveAs2003(string dir, string fileName)
        {
            string filePath = Path.Combine(dir, fileName + ".xls");

            mWorkBook.SaveAs(filePath,
                             Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value);

            mExcelApp.DisplayAlerts = true;

            return filePath;

        }

        public string SaveAs2007(string dir, string fileName)
        {
            string filePath = Path.Combine(dir, fileName + ".xlsx");

            mWorkBook.SaveAs(filePath,
                             Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value,
                             Missing.Value);

            mExcelApp.DisplayAlerts = true;

            return filePath;

        }

        private void AutofitColumns(Microsoft.Office.Interop.Excel.Worksheet ws, string colStart, string colFinish)
        {
            //AutoFit columns A:D.
            Microsoft.Office.Interop.Excel.Range oRng;
            oRng = ws.get_Range(colStart, colFinish);
            oRng.EntireColumn.AutoFit();
        }

        private void AddAccelelations(string line)
        {
            List<string> nums = SplitLine(line);
            for (int i = 0; i < nums.Count; i++)
            {
                mATH.Add(nums[i]);
            }
        }

        private List<string> SplitLine(string line)
        {
            char[] chars = line.ToCharArray();
            List<string> acc = new List<string>();

            if (chars.Length > 72)
            {
                for (int i = 0; i < chars.Length; i++)
                {
                    string num = line.Substring(i, 9);
                    Console.WriteLine(num);
                    acc.Add(num);
                    i = i + 8;
                    if (acc.Count == 8)
                    {
                        return acc;
                    }
                }
            }

            return acc;
        }

        private bool IsValidLine(string line)
        {
            bool valid;
            valid = SplitLine(line).Count == 8;
            return valid;
        }

        private void RemoveDoubleSpaces(ref string line)
        {
            line = line.Trim();
            while (line.Contains("  "))
            {
                line = Regex.Replace(line, "  ", " ");
            }
        }
    }
}
